/**设置单条线的数据源*/
const setOneLine = (map, source, coordinates) => {
    map.addSource(source, {
        type: "geojson",
        data: {
            type: "Feature",
            properties: {},
            geometry: {
                type: "LineString",
                coordinates: coordinates,
            },
        },
    });

}

/**设置多条线的数据源*/
const setLine = (map, source, coordinates) => {
    let features = coordinates.map((e) => {
        return {
            type: 'Feature',
            properties: {},
            geometry: {
                type: 'LineString',
                coordinates: e,
            }
        }
    })
    map.addSource(source, {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: features
        }
    })
}

/**
 * 设置文字
 */
const setText = (map, source, data) => {
    delSource(map, source);
    map.addSource(source.source, data);
};


/**
 * 获取线 GeoJSON
 * @param list
 * @returns {{features: *[], type: string}}
 */
const getLines = (list) => {
  const newList = JSON.parse(JSON.stringify(list));
  const features = newList.map((row) => {
    const geometry = {
      type: 'LineString',
      coordinates: row.pipeLocations.map((item) => {
        return [item.longitude * 1, item.latitude * 1];
      })
    };
    delete row.pipeLocations;
    return {
      type: 'Feature',
      properties: row,
      geometry
    };
  });
  return features;
};


/**
 * GeoJSON
 * @param features
 * @returns {{features: *[], type: string}}
 */
const getGeoJSON = (features = []) => {
  return {
    type: 'geojson',
    data: {
      type: 'FeatureCollection',
      features
    }
  };
};

/**
 * 添加数据源
 * @param map
 * @param layer
 * @param data
 */
const addSource = (map, layer, data) => {
    delSource(map, layer);
    map.addSource(layer.source, data);
};


/**
 * 删除数据源
 * @param map
 * @param layer
 */
const delSource = (map, layer) => {
    if (map.getSource(layer.source)) {
        map.removeSource(layer.source);
    }
};

/**
 * 删除图层
 * @param map
 * @param layer
 */
const delLayer = (map, layer) => {
  if (map.getLayer(layer.id)) {
    map.removeLayer(layer.id);
  }
};




export default {
    setOneLine,
    setLine,
    delLayer,
    getLines
}